package com.cch.cooperation.biz.common.valid.util;

import cn.hutool.core.util.ObjectUtil;
import com.cch.cooperation.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Collection;
import java.util.Set;

/**
 * bean字段校验，暂不支持嵌套
 *
 * @author cch on 2020/11/06
 **/
@Slf4j
public class ValidUtil {

    private static Validator validator = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(false)
            .buildValidatorFactory()
            .getValidator();

    public static void valid(Object obj) throws BizException {
        if (ObjectUtil.isNull(obj)) {
            return;
        }
        if (obj instanceof Collection) {
            validCollection((Collection) obj);
            return;
        }
        validObject(obj);
    }

    public static void validCollection(Collection collection) throws BizException {
        for (Object obj : collection) {
            validObject(obj);
        }
    }

    public static void validObject(Object obj) throws BizException {
        Set<ConstraintViolation<Object>> results = validator.validate(obj, Default.class);
        if (results.size() > 0) {
            for (ConstraintViolation<Object> result : results) {
                throw new BizException(result.getMessage());
            }
        }
    }

}
